import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:play_lab/constants/my_status.dart';
import 'package:play_lab/constants/my_strings.dart';
import 'package:play_lab/core/route/route.dart';
import 'package:play_lab/core/utils/dimensions.dart';
import 'package:play_lab/core/utils/my_color.dart';
import 'package:play_lab/core/utils/styles.dart';
import 'package:play_lab/data/controller/request/request_controller.dart';
import 'package:play_lab/data/repo/request/request_repo.dart';
import 'package:play_lab/data/services/api_service.dart';
import 'package:play_lab/view/components/app_bar/custom_appbar.dart';
import 'package:play_lab/view/components/circle_icon_button.dart';
import 'package:play_lab/view/components/custom_loader/custom_loader.dart';
import 'package:play_lab/view/components/image/my_image_widget.dart';
import 'package:play_lab/view/components/no_data_widget.dart';

class MyRequestScreen extends StatefulWidget {
  const MyRequestScreen({super.key});

  @override
  State<MyRequestScreen> createState() => _MyRequestScreenState();
}

class _MyRequestScreenState extends State<MyRequestScreen> {
  ScrollController scrollController = ScrollController();

  fetchData() {
    Get.find<RequestController>().myRequestList();
  }

  void _scrollListener() {
    if (scrollController.position.pixels == scrollController.position.maxScrollExtent) {
      fetchData();
    }
  }

  @override
  void initState() {
    Get.put(ApiClient(sharedPreferences: Get.find()));
    Get.put(RequestRepo(apiClient: Get.find()));
    final controller = Get.put(RequestController(repo: Get.find()));

    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.clear();
      controller.myRequestList();
      scrollController.addListener(_scrollListener);
    });
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: true,
      onPopInvokedWithResult: (didPop, result) {
        Get.find<RequestController>().clear();
      },
      child: Scaffold(
        appBar: CustomAppBar(
          title: MyStrings.myRequest,
          actions: [
            CircleIconButton(
              backgroundColor: MyColor.primaryColor,
              child: Icon(Icons.add),
              onTap: () {
                Get.toNamed(RouteHelper.makeRequestScreen)?.then((value) {
                  Get.find<RequestController>().clear();
                  Get.find<RequestController>().myRequestList();
                });
              },
            ),
            SizedBox(width: Dimensions.space20),
          ],
        ),
        backgroundColor: MyColor.colorBlack,
        body: Padding(
          padding: Dimensions.screenPaddingHV,
          child: GetBuilder<RequestController>(
            builder: (controller) {
              if (controller.isLoading) {
                return CustomLoader();
              }
              if (controller.myRequests.isEmpty && !controller.isLoading) {
                return NoDataFoundScreen(
                  message: MyStrings.noItemRequestedYet,
                );
              }
              return RefreshIndicator(
                onRefresh: () async {
                  controller.clear();
                  controller.myRequestList();
                },
                child: ListView.separated(
                  physics: BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
                  controller: scrollController,
                  separatorBuilder: (context, index) => SizedBox(height: Dimensions.space15),
                  itemCount: controller.myRequests.length + 1,
                  itemBuilder: (context, index) {
                    if (index == controller.myRequests.length) {
                      return Center(
                        child: controller.hasNext() ? const CircularProgressIndicator(color: MyColor.primaryColor) : const SizedBox(),
                      );
                    }
                    final item = controller.myRequests[index];
                    return Container(
                      padding: EdgeInsets.all(Dimensions.space10),
                      decoration: BoxDecoration(
                        color: MyColor.cardBg,
                        borderRadius: BorderRadius.circular(Dimensions.mediumRadius),
                      ),
                      child: Column(
                        children: [
                          Row(
                            spacing: Dimensions.space10,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              MyImageWidget(imageUrl: "${controller.imagePath}${item.imagePath}", height: 180, width: 120),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Text(item.item ?? "", style: boldDefault.copyWith(), maxLines: 2, overflow: TextOverflow.ellipsis),
                                    SizedBox(height: Dimensions.space5),
                                    Text(item.overview ?? "", style: mulishLight.copyWith(color: MyColor.primaryText2), maxLines: 5, overflow: TextOverflow.ellipsis),
                                    SizedBox(height: Dimensions.space20),
                                    Align(
                                      alignment: Alignment.centerRight,
                                      child: Container(
                                        padding: EdgeInsets.symmetric(horizontal: Dimensions.space10),
                                        decoration: BoxDecoration(
                                          color: MyStatus.requestItemStatus(item.status.toString()).color.withValues(alpha: 0.01),
                                          border: Border.all(color: MyStatus.requestItemStatus(item.status.toString()).color, width: .5),
                                          borderRadius: BorderRadius.circular(Dimensions.cardRadius),
                                        ),
                                        child: Text(MyStatus.requestItemStatus(item.status.toString()).status, style: mulishMedium.copyWith(color: MyStatus.requestItemStatus(item.status.toString()).color)),
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ),
                          SizedBox(height: Dimensions.space5),
                          Row(
                            children: [
                              Expanded(child: Container()),
                              Container(
                                padding: EdgeInsets.symmetric(horizontal: Dimensions.space20, vertical: Dimensions.space8),
                                decoration: BoxDecoration(
                                  color: MyColor.colorBlack,
                                  borderRadius: BorderRadius.circular(Dimensions.extraRadius),
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  spacing: Dimensions.space10,
                                  children: [
                                    iconWIdget(
                                      text: item.upVotes ?? "0",
                                      icon: Icons.thumb_up_outlined,
                                      onTap: () => controller.vote(index, myRequest: true),
                                    ),
                                    iconWIdget(
                                      text: item.downVotes ?? "0",
                                      icon: Icons.thumb_down_outlined,
                                      onTap: () => controller.vote(index, isUpVote: false, myRequest: true),
                                    ),
                                    iconWIdget(
                                      text: "",
                                      icon: item.userSubscribe == "true" ? Icons.notifications : Icons.notifications_outlined,
                                      onTap: () => controller.subscribe(index, myRequest: true),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    );
                  },
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget iconWIdget({
    required String text,
    required IconData icon,
    required VoidCallback onTap,
  }) =>
      InkWell(onTap: onTap, customBorder: CircleBorder(), child: Row(children: [Text(text), SizedBox(width: Dimensions.space5), Icon(icon)]));
}
